import {ActionType, ModalForm, PageContainer, ProFormText, ProTable} from "@ant-design/pro-components";
import moment from "moment";
import React, {useEffect, useRef, useState} from "react";
import {Button, DatePicker, Form, message, Spin, Upload, type UploadProps} from "antd";
import {addOrUpdateAudioCategory, getAudioCategories, uploadFile} from "@/services/audio/audio";
import {UploadOutlined} from "@ant-design/icons";
import {AUDIO} from "@/services/audio/audio.typings";
import {DEPARTMENT_MANAGE, DEPARTMENT_SYS_MANAGE, SALES_MANAGE} from "@/global.style";
import initialState from "@@/plugin-initialState/@@initialState";
import {useModel} from "@@/exports";

const Category = () => {
  const {initialState, setInitialState} = useModel('@@initialState');

  const [loading, setLoading] = useState(false);

  const actionRef = useRef<ActionType>();
  const formRef = useRef();

  const [currentIndex, setCurrentIndex] = useState(0)
  const [size, setSize] = useState(10)
  const [isEdit, setIsEdit] = useState(false)
  const [editModal, setEditModal] = useState(false)
  const [record, setRecord] = useState(null)
  const [file, setFile] = useState(null)

  const {RangePicker} = DatePicker;
  const shouldShowAddOrUpdate = (roles) => {
    const restrictedRoles = [DEPARTMENT_SYS_MANAGE];
    return !roles.some(role => restrictedRoles.includes(role));
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      hideInSearch: true,
    }, {
      title: '类别图片',
      dataIndex: 'imageUrl',
      hideInSearch: true,
      render: (text) => <img src={text} style={{width: 50, height: 50}}/>
    }, {
      title: '类别名称',
      dataIndex: 'name',
    }, {
      title: '类别音频数量',
      dataIndex: 'audioCount',
      hideInSearch: true,
    }, {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      hideInTable: true,
      renderFormItem: (_, {type, defaultRender, ...rest}, form) => {
        // 当表单项被渲染时，使用RangePicker组件
        if (type === 'form') {
          return <RangePicker showTime={{format: 'HH:mm:ss'}} format="YYYY-MM-DD HH:mm:ss" {...rest} />;
        }
        // 使用默认渲染逻辑
        return defaultRender(_);
      },
    }, {
      title: '创建时间',
      dataIndex: 'createdTime',
      hideInSearch: true,
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss')
    }, {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        shouldShowAddOrUpdate(initialState.currentUser.roles) && (<a key="edit" onClick={() => {
          console.log('edit', record)
          setRecord(record)
          setFile(null)
          setIsEdit(true)
          setEditModal(true)

        }}>编辑</a>),
      ],
    }
  ]

  const beforeUpload = (file) => {
    const isPng = file.type === 'image/png' || file.type === 'image/jpeg';
    console.log('file type', file.type)
    if (!isPng) {
      message.error('只能上传 png/jpg 文件!');
    }
    // return isPng || Upload.LIST_IGNORE;
    return false
  };
  const props: UploadProps = {
    onChange(info) {
      console.log(info.fileList)
      setFile(info.fileList[info.fileList.length - 1]); // 设置最新的一个文件为当前文件
    },
  };
  return (
    <PageContainer title={'音频类型'}>
      <Spin spinning={loading} tip="加载中...">
        <ProTable
          columns={columns}
          actionRef={actionRef}
          request={async (params) => {
            const reqParams: AUDIO.GetAudioCategoriesParams = {
              ...params,
              page: currentIndex,
              size
            }
            if (reqParams.createdTime) {
              reqParams.searchTimeStart = String(params.createdTime).split(',')[0]
              reqParams.searchTimeEnd = String(params.createdTime).split(',')[1]
            }
            const res = await getAudioCategories(reqParams);
            return {
              data: res.data.records,
              success: true,
              total: res.data.total
            }
          }}
          pagination={{
            pageSize: size,
            onChange: (page) => setCurrentIndex(page),
          }}
          toolBarRender={() => [
            shouldShowAddOrUpdate(initialState.currentUser.roles) && (<Button
              key="button"
              onClick={() => {
                setEditModal(true)
                setIsEdit(false)
                setRecord(null)
                setFile(null)
                formRef.current?.resetFields()
                // actionRef.current?.reload();
              }}
              type="primary"
            >
              新建类别
            </Button>),
          ]}
        />

        <ModalForm
          formRef={formRef}
          title={isEdit ? '编辑类别' : '新建类别'}
          open={editModal}
          onOpenChange={(open) => {
            setEditModal(open)
            if (open && isEdit) {
              formRef.current?.setFieldsValue({
                name: record.name,
                tag: record.tag
              })
            }
          }}
          onFinish={async (values) => {
            console.log('submit', values)
            //先上传文件
            if (file === null) {
              message.error('请上传图片文件')
              return false
            }
            console.log('file', file)
            const formData = new FormData();
            formData.append('file', file);
            const res = await uploadFile(formData)
            if (res.code !== 1) {
              console.log('1111111111111111')
              message.error('上传文件失败,' + res.msg)
              return false
            }
            console.log('upload file', res.data)
            const params: AUDIO.AddOrUpdateAudioCategoryParams = {
              ...values,
              imageUrl: res.data[0],
            }
            if (isEdit) {
              params.id = record.id
            }
            const ret = await addOrUpdateAudioCategory(params)
            if (ret.code === 1) {
              message.success('操作成功')
              actionRef.current?.reload()
              return true
            } else {
              message.error('操作失败')
              return false
            }
          }}
        >
          <Form labelCol={{span: 4}}>
            <Form.Item label="分类图片" name="file">
              <Upload {...props} beforeUpload={beforeUpload}>
                <Button icon={<UploadOutlined/>}>点击上传</Button>
              </Upload>
            </Form.Item>
          </Form>
          <div style={{marginTop: '100px'}}>
            <ProFormText label="类别名称" name="name"
                         rules={[
                           {
                             required: true,
                             message: '请输入类别名称',
                           }
                         ]}
            />
            <ProFormText label="不可跳过收听起始标号" name="tag"
                         rules={[
                           {
                             pattern: /^[0-9]+$/,
                             message: '请输入数字',
                           },
                           {
                             required: true,
                             message: '请输入不可跳过收听起始标号',
                           }
                         ]}
            />
          </div>
        </ModalForm>
      </Spin>
    </PageContainer>
  )
}

export default Category;
